package org.study;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClientDemo {

    public static void main(String[] args) {
        try {
            // 创建一个 Socket 连接到服务器的指定端口
            Socket socket = new Socket("localhost", 8080);

            System.out.println("已连接到服务器");

            // 获取输出流，用于向服务器发送数据
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            // 获取输入流，用于接收服务器发送的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput;

            // 循环发送用户输入的消息到服务器，并打印服务器的回应
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("服务器回应：" + in.readLine());
            }

            // 关闭连接
            socket.close();

        } catch (UnknownHostException e) {
            System.out.println("无法找到主机。请检查主机名是否正确。");
            System.exit(1);
        } catch (IOException e) {
            System.out.println("I/O 异常: " + e.getMessage());
            System.exit(1);
        }
    }



}
